﻿/*
 *  Copyright (c) 2014 UTUO WMFL, All rights reserved.
 *  http://www.wmfl.cn
 *
 *  @verson 1.0
 *  @author rguanghui(<a href="mailto:rguanghui.stupid@gmail.com">rguanghui.stupid@gmail.com</a>)
 *  @description some text for waiting write
 */


(function($){
  
  // 鼠标经过文本输入框预览图片
  $.fn.extend({
    imagePreview: function(configs){
      var img = $("<img>");
      $(this).on("mouseover", function(e){
          $(this).parent().css({
              "position": "relative"
          });
          img.attr("src", $(this).val());
          img.css({
              "position": "absolute",
              "top": 0,
              "left": "100%",
              "maxWidth": "200px"
          });
          img.appendTo($(this).parent());
      }).on("mouseout", function(e){
          img.remove();
      });
    }
  });
  
  //消息通知(固定在浏览器顶部的居中文本)， type类型有: success/info/warning/danger（默认info）， msg: 弹出消息（默认无）
  $.fn.extend({
    alertMsg: function( configs ) {
      var defaults = {
        type: "info",
        msg: ""
      };
      configs = $.extend({}, defaults, configs);
      var oMsg = $( "<div class='alert alert-" + configs.type + " alert-dismissable'>" + configs.msg
             + "<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;</button>"
             + "</div>" ).appendTo( document.body );
      oMsg.css({
        position: "fixed",
        zIndex: "9999",
        top: "50px",
        maxWidth: "500px",
        overflow: "hidden",
        left: "50%",
        WebkitTransform: "translateX(-50%)",
        display: "none",
        borderRadius: "0 0 4px 4px"
      });
      oMsg.slideDown(600).delay(2000).slideUp(600, function(){ oMsg.remove() });
    }
  });
  
  //上传图片预览
  $.fn.extend({
    uploadImagesPreview: function( configs ) {
      var defaults = {
        data: []
      }
      //合并参数
      configs = $.extend({}, defaults, configs);
      
      $(this).data( "data", configs.data );
      
      this.bind( "refresh", function () {
        var data = $( this ).data( "data" );
          configs.insertContent.val( data.join("\n") );
          //添加图片预览列表
          var html = "";
          for(var i=0, len = data.length; i< len; i++){
            
            html += "<div class='image-item'>"
                   +"<img src='"+ data[i] +"'>"
                   +"<div class='black-mask'></div>"
                   +"<div class='icon-remove'></div>"
                   +"</div>";
          }
          $( this ).html( html );
        });
      
      //初始化
      this.trigger("refresh");
      
      //代理事件
      $(this).delegate("div.image-item", "mouseenter", function(){
        $(this).find( ".black-mask" ).show();
        $(this).find( ".icon-remove" ).show();
      });
      $(this).delegate("div.image-item", "mouseleave", function(){
        $(this).find( ".black-mask" ).hide();
        $(this).find( ".icon-remove" ).hide();
      });
      
      //点击删除，存入数据，刷新。
      var _this = $(this);
      $(this).delegate("div.image-item", "click", function(){
        $(this).remove();
        var thenArray = [];
        _this.find("div.image-item").each(function(i){
          thenArray.push( $(this).find("img").attr("src") );
        });
        _this.data("data", thenArray);
        _this.trigger("refresh");
      });
    },
    addImageData : function(data) {
      var dat = $(this).data("data");
      dat.push( data[0] );
      $( this ).data( "data", dat );
      this.trigger( "refresh" );
    }
  });
   
  //复制粘贴
  $.fn.extend({
    copyPaste: function( configs ) {
      var clip = new ZeroClipboard.Client();
      ZeroClipboard.setMoviePath("/Public/Style/Common/js/ZeroClipboard.swf");
      clip.setText( configs.text );
      clip.glue( configs.id );
      clip.addEventListener("onComplete", function(){
        $().alertMsg({type: "success", msg: "复制成功，使用 ctrl+v 复制到别处吧！"});
      });  
    }
  });
})(jQuery);

//给所有表单进行表单验证，根据data-loading-txt,data-ajax-url, 进行ajax提交
$(function() {
  $(".form-horizontal").Validform({
    tiptype: 3,
    datatype: {
      "phone" : /^(([04]\d{2,3}[-]?\d{7,8})|(1[34578]\d{9}))$/
    },
    callback:function(form){
      var _this = $(form).find("button[data-loading-txt]"); 
      var loadingGifUrl = "/Public/Style/Common/images/loading-black.gif",
          ajaxUrl = $(_this).attr("data-ajax-url"),
          callback = $(_this).attr("data-action-callback"),
          actionBefore = $(_this).attr("call-action-before"),
          tip = $(_this).parent().find("span");
      
      tip && tip.remove();
      
      var oSpan = $("<span><img src=" + loadingGifUrl + ">" + $(_this).attr("data-loading-txt") + "</span>").appendTo( $(_this).parent() );
      
      $( _this ).attr( "disabled", true );
      
      actionBefore && eval(actionBefore+".apply(_this,[])") ;
      
      $.post(ajaxUrl, $(".form-horizontal").serialize(), function(data){
        if( data.error == 1 ) {
          oSpan.html("<span class='tip tip-danger'>" + data.msg + "</span>")
        } else if ( data.error == 0 ) {
          oSpan.html("<span class='tip tip-success'>" + data.msg + "</span>");
          try {
            callback && actionCallback( data.extra ); 
          } catch ( e ) {
            callback && eval( callback + "()" );
          };
          data.redirect && ( setTimeout( function(){ window.location = data.redirect.url } ,  data.redirect.delay) );
        };
        setTimeout( function() { $(_this).removeAttr("disabled") }, 2000);
      }, "json");
      
      return false;
    }
  });
});

/* class中含有.actionds执行操作：删除，恢复，彻底删除
 * data-action-id 确定操作的数据
 * data-action-txt 操作时提示的文字
 * data-action-url 操作的地址
 * data-action-delete 是否是彻底删除
 */
$(function(){
  $(".actionds").click(function(){
    var actionUrl = $(this).attr("data-action-url"),//执行的URL
      actionId = $(this).attr("data-action-id"),//执行的id
      actionTxt = $(this).attr("data-action-txt"),//执行动作时的提示文字
      actionDel = $(this).attr("data-action-delete"),//是否是彻底删除按钮
      actionStatus = $(this).attr("data-action-status"),//设置用户状态用
      actionSuccess = $(this).attr("call-action-success")
      loadingGifUrl = "/Public/Style/Common/images/loading-black.gif",//loading gif 地址
      tip = $(this).parent().find("span"),
      _this = this;
    
    if( actionDel ) {
      if( !window.confirm("彻底删除后无法恢复，确定要删除么？") ) { return; };
    };
    
    tip && tip.remove();
    
    $(this).attr("disabled", true);
    
    var oSpan = $("<span style='position:absolute' class='tip tip-info'><img src=" + loadingGifUrl + ">" +actionTxt+ "</span>").appendTo($(this).parent());
    
    $.post(actionUrl, {id: actionId}, function(data){
      if( data.error == 0 ) {
        oSpan.html( data.msg );
        setTimeout(function() {
          actionSuccess && eval(actionSuccess+".apply(_this,[])") ;
          actionSuccess || $(_this).parent().parent().fadeOut(500);
        }, 1500);
      } else {
        oSpan.removeClass( "tip-info" ).addClass( "tip-danger" );
        oSpan.html( data.msg );
        $(_this).removeAttr( "disabled" );
      }
    }, "json");

  });
});

/* class中含有.action-status执行更改状态操作
 * data-action-id 确定操作的数据
 * data-action-txt 操作时提示的文字
 * data-action-url 操作的地址
 */
$(function(){
  $(".action-status").click(function(){
	  box(this,$(this),"status")
  
    
  });
  /**/
  $(".action-open").click(function(){
	    box(this,$(this),"open")
	  });
  function box(othis,obj,onum){
	  var actionUrl = obj.attr("data-action-url"),//执行的URL
      actionId = obj.attr("data-action-id"),//执行的id
      actionTxt = obj.attr("data-action-txt"),//执行动作时的提示文字
      actionStatus = obj.attr("data-action-status"),//设置用户状态用
      actionStatusTxt = obj.attr("data-action-status-txt").split(" "), //更改状态时替换的文字
      loadingGifUrl = "http://simlib.sinaapp.com/newwmfl/images/wmfl-loading-black.gif",//loading gif 地址
      tip = obj.parent().find("span"),
      _this = othis;

    tip && tip.remove();
    
    obj.attr("disabled", true);
    
    var oSpan = $("<span style='position:absolute' class='tip tip-info'><img src=" + loadingGifUrl + " /> " +actionTxt+ "</span>").appendTo(obj.parent());
    
    var objj = {};
    objj.id = actionId;
    objj[onum] = actionStatus;
    $.post(actionUrl, objj, function(data){
      
      if( data.error == 0 ) {
    	console.log("..");
        oSpan.html(data.msg).delay(1000).fadeOut(400);
        if( parseInt(actionStatus) ){
          $(_this).html(actionStatusTxt[0]);
          $(_this).parent().siblings("."+onum).html(actionStatusTxt[1]);
          $(_this).attr("data-action-status", "0");
        } else {
          $(_this).html(actionStatusTxt[1]);
          $(_this).parent().siblings("."+onum).html(actionStatusTxt[0]);
          $(_this).attr("data-action-status", "1");
        };
        
      } else {
        oSpan.removeClass( "tip-info" ).addClass( "tip-danger" );
        oSpan.html( data.msg );
        $(_this).removeAttr("disabled");
        
      };
      
      $(_this).removeAttr("disabled");
      
    }, "json");
  }
});

/*
 * 自动创建表情列表
 */
$(function(){
  
  var start = 0, end = 0;
  
  var getStart = function(){
    if( window.getSelection ) {
      start = window.getSelection().anchorOffset;
      end = window.getSelection().focusOffset;
    };
  };
  $("#content").blur(function(){
    getStart();
  });
  
  $("#icon-emtion").click(function(){
    var emtionList = "",
      ul = $(this).parent().find("ul");
    for(var i=0; i<105; i++)
    {
      emtionList += "<li class='emtion-item'>"
             +"<i class='emtion-i'data-gifurl='http://5.wmei.sinaapp.com/Public/Style/My/Default/images/emtions/" + i + ".gif' style='background-position: " + (-i*24) +"px 0'></i>"
             +"</li>";
    }
    
    if ( ul.length ){
      if( ul.is(":hidden") ) {
        ul.fadeIn(400);
      } else {
        ul.fadeOut(400);
      }
    } else {
      $( "<ul class='emtions'></ul>" ).html( emtionList ).appendTo( $(this).parent() );
    }
    
    $(".emtions").delegate( "i", "click", function() {
      
      var oldHtml = $( "#content" ).html(),
        img = "<img src=' " + $(this).attr('data-gifurl') + " '/>",
        content = $("#content");
      
      var newHtml = oldHtml.substr( 0, start ) + img + oldHtml.substr( end );
      
      $( "#content" ).html( newHtml );
    } );
  });
});